import { useState, useEffect, useRef } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import './App.css';

export default function Location() {
  const [city, setCity] = useState(null);
  const [location, setLocation] = useState('');
  const [address, setAddress] = useState('');
  const [searchTerm, setSearchTerm] = useState('');
  const [searchMarker, setSearchMarker] = useState(null);
  const [drivingResult, setDrivingResult] = useState(null);
  const mapRef = useRef(null);
  const searchButtonRef = useRef(null);

  useEffect(() => {
    window._AMapSecurityConfig = {
      securityJsCode: "bb0431ae85f5a0ecbb06263f2fe0aeb7",
    };

    const initializeMap = async () => {
      try {
        const AMap = await AMapLoader.load({
          key: "c205087c842a7a99c347e57c77170b76",
          version: "2.0",
          plugins: [
            "AMap.Scale",
            "AMap.Geolocation",
            "AMap.Geocoder",
            "AMap.Marker",
            "AMap.Driving",
          ],
        });

        const mapInstance = new AMap.Map("container", {
          zoom: 11,
          center: [116.397428, 39.90923],
        });
        mapRef.current = mapInstance;

        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0,
          convert: true,
          showButton: true,
        });
        mapInstance.addControl(geolocation);

        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete' && result.info === 'SUCCESS') {
            const lnglat = result.position;
            setLocation(`${lnglat.lng},${lnglat.lat}`);
            mapInstance.setCenter(lnglat);
            mapInstance.setZoom(15);

            const marker = new AMap.Marker({
              position: lnglat,
              title: "当前位置",
            });
            mapInstance.add(marker);

            const geocoder = new AMap.Geocoder();
            geocoder.getAddress(lnglat, (status, result) => {
              if (status === 'complete' && result.info === 'OK') {
                setAddress(result.regeocode.formattedAddress);
                setCity(result.regeocode.addressComponent.city);
              } else {
                console.error('地址解析失败:', result.message);
              }
            });
          } else {
            console.error('获取用户位置时出错:', result.message);
          }
        });

        // 确保在使用 Driving 插件之前，地图已经完全初始化
        const driving = new AMap.Driving({
          map: mapInstance,
          panel: "panel",
        });

        const handleSearch = () => {
          if (!searchTerm) return;

          const geocoder = new AMap.Geocoder();
          geocoder.getLocation(searchTerm, (status, result) => {
            if (status === 'complete' && result.info === 'OK') {
              if (searchMarker) {
                mapInstance.remove(searchMarker);
              }

              const { geocodes } = result;
              if (geocodes.length > 0) {
                const { location: targetLocation, address: targetAddress } = geocodes[0];

                // 确保地图对象存在且已正确初始化
                if (mapInstance) {
                  mapInstance.setCenter(targetLocation);
                  mapInstance.setZoom(12);
                } else {
                  console.error('地图对象未正确初始化');
                }

                const marker = new AMap.Marker({
                  position: targetLocation,
                  title: `城市: ${targetAddress}`,
                });
                mapInstance.add(marker);
                setSearchMarker(marker);

                // 尝试多次获取当前位置以提高准确性
                let accurateStartLocation = null;
                let attempts = 0;
                const maxAttempts = 3;
                const getAccurateLocation = () => {
                  geolocation.getCurrentPosition((status, result) => {
                    if (status === 'complete' && result.info === 'SUCCESS') {
                      accurateStartLocation = result.position;
                      // 一旦获取到准确位置，立即进行路线规划
                      if (accurateStartLocation) {
                        // 确保 driving 对象存在且已正确初始化
                        if (driving) {
                          driving.search(accurateStartLocation, targetLocation, (status, result) => {
                            if (status === 'complete') {
                              console.log('驾车路线规划成功:', result);
                              setDrivingResult(result);
                            } else {
                              console.error('驾车路线规划失败:', result);
                            }
                          });
                        } else {
                          console.error('Driving 对象未正确初始化');
                        }
                      }
                    } else {
                      if (attempts < maxAttempts) {
                        attempts++;
                        getAccurateLocation();
                      } else {
                        console.error('无法获取准确的起始位置');
                      }
                    }
                  });
                };
                getAccurateLocation();
              } else {
                console.warn('未找到相关城市');
              }
            } else {
              console.warn('地理编码失败:', result.message);
            }
          });
        };

        if (searchButtonRef.current) {
          searchButtonRef.current.addEventListener('click', handleSearch);
        }

        return () => {
          if (mapInstance) {
            mapInstance.destroy();
          }
          if (searchButtonRef.current) {
            searchButtonRef.current.removeEventListener('click', handleSearch);
          }
        };
      } catch (e) {
        console.error('地图加载出错:', e);
      }
    };

    initializeMap();
  }, [searchTerm]);

  return (
    <div>
      <div>
        {/* <p>您所在的城市: {city}</p> */}
        {/* <p>您的具体位置是: {address || '未知'}</p> */}
        我的位置：
        <input
          type="text"
          placeholder="您所在的城市"
          value={address}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ width: '200px', padding: '8px', marginRight: '8px' }}
        />
      </div>
      <div style={{ display: 'flex', alignItems: 'center' }}>
        目标位置：
        <input
          type="text"
          placeholder="输入您想去的城市"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          style={{ width: '200px', padding: '8px', marginRight: '8px' }}
        />
        <button ref={searchButtonRef} style={{ padding: '8px 16px' }}>前往</button>
      </div>
      <div id="container" className='container' style={{ height: "60vh", marginTop: '16px' }} />
      <div id="panel" style={{ height: '30vh', overflow: 'auto', marginTop: '16px' }}></div>
    </div>
  );
}